package com.ht.api.call.func.impl.sop;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 删除sop的前置函数
 * @author asq
 * @createTime 2025年3月20日 10:05:40
 */
@Slf4j
public class SopDelBeforeFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "删除sop的前置函数";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();

		String sopId = param.getStr("main_id");

		DbList stageList = Db.createSqlParser("stage").where("sop_id", sopId).query(ds);
		if (stageList != null && stageList.size() > 0) {
			List<String> stageIds = new ArrayList<>();
			for (Entity entity : stageList) {
				stageIds.add(entity.getStr("main_id"));
			}

			Long userCount = Db.createSqlParser("ad_plan_user").where("source_id", "in", stageIds).count(ds);
			if (userCount != null && userCount >0) {
				throw new HtException("旅程已使用，不能删除，只能停用！");
			}

			List<Entity> dataList = new ArrayList<>();
			for (Entity stage : stageList) {
				Db.delete(ds, stage);
				Db.delete(ds, Entity.create("ad_plan").set("main_id", stage.getStr("plan_id")));
				Db.delete(ds, Entity.create("ad_campaign").set("main_id", stage.getStr("campaign_id")));

				DbList itemList = Db.createSqlParser("ad_campaign_item").select("main_id").where("campaign_id", stage.getStr("campaign_id")).query(ds);
				for (Entity entity : itemList) {
					entity.set("sys_deleted", 0);
					dataList.add(entity);
				}
			}
			Db.insertBatchWithStream(me.getStreamLoadConfig(), dataList);
		}

		return JSONUtil.createObj();
	}
}
